package topic.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;
import com.makeramen.roundedimageview.RoundedImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import common.Constant;
import https.InterNetController;
import mainFragment.activity.CollegeIndex;
import mainFragment.adapter.MyGridViewAdapter;
import topic.activity.SingleTopic;
import topic.bean.TopicGroupBean;
import personalPage.activity.PersonalPage;
import utils.ShowImageUtils;
import view.MyConfirmDialog;
import view.MyGridView;
import view.MyImageLoader;

/**
 * Created by Administrator on 2017/3/11.
 * 帖子列表适配器
 */

public class TopicAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<TopicGroupBean.BlogListBean> arrayList;
    private OnTopicDetailListener onTopicDetailListener;

    public TopicAdapter(Context context, ArrayList<TopicGroupBean.BlogListBean> arrayList, OnTopicDetailListener onTopicDetailListener) {
        this.context = context;
        this.arrayList = arrayList;
        this.onTopicDetailListener = onTopicDetailListener;
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final MyHolder myHolder;
        if (convertView == null) {
            myHolder = new MyHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.college_topic_item, null);
            myHolder.college_topic_item_headLayout = (RelativeLayout) convertView.findViewById(R.id.college_topic_item_headLayout);
            myHolder.college_topic_item_headIma = (RoundedImageView) convertView.findViewById(R.id.college_topic_item_headIma);
            myHolder.college_topic_item_name = (TextView) convertView.findViewById(R.id.college_topic_item_name);
            myHolder.college_topic_item_addr = (TextView) convertView.findViewById(R.id.college_topic_item_addr);
            myHolder.college_topic_item_content = (TextView) convertView.findViewById(R.id.college_topic_item_content);
            myHolder.college_topic_item_time = (TextView) convertView.findViewById(R.id.college_topic_item_time);
            myHolder.college_topic_item_zan = (TextView) convertView.findViewById(R.id.college_topic_item_zan);
            myHolder.college_topic_item_comment = (TextView) convertView.findViewById(R.id.college_topic_item_comment);
            myHolder.college_topic_item_gridView = (MyGridView) convertView.findViewById(R.id.college_topic_item_gridView);
            myHolder.college_topic_item_delete = (TextView) convertView.findViewById(R.id.college_topic_item_delete);
            convertView.setTag(myHolder);
        } else {
            myHolder = (MyHolder) convertView.getTag();
        }
        if (arrayList.get(position) != null) {
            MyImageLoader.showImage(arrayList.get(position).getHeadimgurl(), myHolder.college_topic_item_headIma);
            myHolder.college_topic_item_name.setText(arrayList.get(position).getNickname());
            myHolder.college_topic_item_addr.setText(arrayList.get(position).getCity());
            if (!TextUtils.isEmpty(arrayList.get(position).getContent())) {
                myHolder.college_topic_item_content.setVisibility(View.VISIBLE);
                //添加高校或者话题
                if (arrayList.get(position).getCollegeBean() != null) {
                    // 高校
                    if (!TextUtils.isEmpty(arrayList.get(position).getCollegeBean().getId())) {
                        ClickableSpan clickableSpan = new ClickableSpan() {
                            @Override
                            public void onClick(View widget) {
                                Intent i = new Intent(context, CollegeIndex.class);
                                i.putExtra("id", arrayList.get(position).getCollegeBean().getId());
                                context.startActivity(i);
                            }

                            @Override
                            public void updateDrawState(TextPaint ds) {
                                int color = context.getResources().getColor(R.color.common_color);
                                ds.setColor(color);
                                ds.setUnderlineText(false); //去掉下划线
                            }
                        };
                        SpannableString content = new SpannableString("#" + arrayList.get(position).getCollegeBean().getName() + "#" + arrayList.get(position).getContent());
                        content.setSpan(clickableSpan, 0, arrayList.get(position).getCollegeBean().getName().length() + 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                        myHolder.college_topic_item_content.setText(content);
                    }
                } else if (arrayList.get(position).getTopic() != null) {
                    //话题
                    if (!TextUtils.isEmpty(arrayList.get(position).getTopic().getId())) {
                        ClickableSpan clickableSpan = new ClickableSpan() {
                            @Override
                            public void onClick(View widget) {
                                Intent i = new Intent(context, SingleTopic.class);
                                i.putExtra("topicid", arrayList.get(position).getTopic().getId());
                                context.startActivity(i);
                            }

                            @Override
                            public void updateDrawState(TextPaint ds) {
                                int color = context.getResources().getColor(R.color.common_color);
                                ds.setColor(color);
                                ds.setUnderlineText(false); //去掉下划线
                            }
                        };
                        String name = arrayList.get(position).getTopic().getTitle();
                        //当有话题时，显示蓝色
                        SpannableString content = new SpannableString("#" + name + "#" + arrayList.get(position).getContent());
                        content.setSpan(clickableSpan, 0, name.length() + 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                        myHolder.college_topic_item_content.setText(content);
                    }
                } else {
                    myHolder.college_topic_item_content.setText(arrayList.get(position).getContent());
                }
                myHolder.college_topic_item_content.setMovementMethod(LinkMovementMethod.getInstance());
            } else {
                myHolder.college_topic_item_content.setVisibility(View.GONE);
            }
            myHolder.college_topic_item_time.setText(arrayList.get(position).getTime());
            myHolder.college_topic_item_zan.setText(arrayList.get(position).getPrise() + "");
            final int color = context.getResources().getColor(R.color.common_color);
            final int color1 = context.getResources().getColor(R.color.text_color1);
            final Drawable drawable = context.getResources().getDrawable(R.mipmap.college_topic_item_zan_ima);
            final Drawable drawable1 = context.getResources().getDrawable(R.mipmap.college_topic_item_zan_ima1);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            drawable1.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            if (arrayList.get(position).getPrised() != 0) {
                //已经赞了
                myHolder.college_topic_item_zan.setTextColor(color);
                myHolder.college_topic_item_zan.setCompoundDrawables(drawable1, null, null, null);
            } else {
                //还没赞
                myHolder.college_topic_item_zan.setTextColor(color1);
                myHolder.college_topic_item_zan.setCompoundDrawables(drawable, null, null, null);
            }
            final Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case Constant.ERROR_CODE_SUCCESS:
                            if (msg.arg1 == 1) {
                                arrayList.remove(msg.arg2);
                                TopicAdapter.this.notifyDataSetChanged();
                            } else {
                                try {
                                    JSONObject jsonObject = new JSONObject((String) msg.obj);
                                    if (jsonObject != null) {
                                        String error_code = jsonObject.getString("err_code");
                                        if ("0".equals(error_code)) {
                                            myHolder.college_topic_item_zan.setCompoundDrawables(drawable1, null, null, null);
                                            myHolder.college_topic_item_zan.setText((Integer.parseInt((String) myHolder.college_topic_item_zan.getText()) + 1) + "");
                                            myHolder.college_topic_item_zan.setTextColor(color);
                                        } else {
                                            myHolder.college_topic_item_zan.setCompoundDrawables(drawable, null, null, null);
                                            myHolder.college_topic_item_zan.setText((Integer.parseInt((String) myHolder.college_topic_item_zan.getText()) - 1) + "");
                                            myHolder.college_topic_item_zan.setTextColor(color1);
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            };
            if (0 == arrayList.get(position).getShowdelete()) {
                myHolder.college_topic_item_delete.setVisibility(View.GONE);
            } else {
                myHolder.college_topic_item_delete.setVisibility(View.VISIBLE);
                myHolder.college_topic_item_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myHolder.college_topic_item_delete.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                final MyConfirmDialog myConfirmDialog = new MyConfirmDialog(context, R.style.confirmDialog, "确认删除?");
                                myConfirmDialog.show();
                                myConfirmDialog.setConfirmListener(new MyConfirmDialog.ConfirmListener() {
                                    @Override
                                    public void confirm() {
                                        deleteBlog(arrayList.get(position).getBlogid(), handler, position);
                                    }
                                });

                            }
                        });
                    }
                });
            }

            myHolder.college_topic_item_zan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    praise(arrayList.get(position).getBlogid(), handler);
                }
            });
            myHolder.college_topic_item_comment.setText(arrayList.get(position).getComment());
            myHolder.college_topic_item_gridView.setVisibility(View.VISIBLE);
            myHolder.college_topic_item_gridView.setAdapter(new MyGridViewAdapter(context, arrayList.get(position).getImages()));

            myHolder.college_topic_item_gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position1, long id) {
                    ShowImageUtils showImageUtils = new ShowImageUtils();
                    showImageUtils.showImageUtils(context, view, arrayList, position, position1);
                }
            });
            myHolder.college_topic_item_content.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onTopicDetailListener.onTopicDetailListener(position);
                }
            });
            myHolder.college_topic_item_gridView.setOnTouchBlankPositionListener(new MyGridView.OnTouchBlankPositionListener() {
                @Override
                public void onTouchBlank(MotionEvent event) {
                    onTopicDetailListener.onTopicDetailListener(position);
                }
            });
            //点击头像跳转到个人主页
            myHolder.college_topic_item_headLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(context, PersonalPage.class);
                    i.putExtra("userId", arrayList.get(position).getUserid());
                    i.putExtra("type", "app");
                    context.startActivity(i);
                }
            });
            myHolder.college_topic_item_content.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onTopicDetailListener.onTopicDetailListener(position);
                }
            });
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onTopicDetailListener.onTopicDetailListener(position);
                }
            });
        }
        return convertView;
    }


    class MyHolder {
        RelativeLayout college_topic_item_headLayout;//头部点击位置
        RoundedImageView college_topic_item_headIma;//头像
        TextView college_topic_item_name;//姓名
        TextView college_topic_item_addr;//地址
        TextView college_topic_item_content;//内容
        TextView college_topic_item_time;//创建时间
        TextView college_topic_item_zan;//点赞
        TextView college_topic_item_comment;//评论量
        MyGridView college_topic_item_gridView;//图片
        TextView college_topic_item_delete;//删除按钮
    }

    public interface OnTopicDetailListener {
        void onTopicDetailListener(int position);
    }

    private void praise(String blogid, Handler handler) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("blogid", blogid);
        new InterNetController(context, Constant.PRISEBLOG, handler, hashMap, 0, false);
    }

    private void deleteBlog(String blogid, Handler handler, int position) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("blogid", blogid);
        new https.InterNetController(context, Constant.DELETEBLOG, handler, hashMap, 1, position);
    }
}
